"""
图灵机
"""
import collections
import re


class TuringMachine:

    def __init__(self):
        self.transfer_func = collections.defaultdict(collections.defaultdict)

    def readFile(self, filePath):
        with open(filePath, 'r') as f:
            for line in f.readlines():
                # line = line.strip('\n').split()
                line = line.strip('\n')
                line = line.replace(' ', '')
                left, right = line.split('=')

                # left = left.strip()
                # right = right.strip()
                # left = re.split('[ ,]', left)
                # right = re.split('[ ,]', right)
                left = left.split(',')
                right = right.split(',')
                # map(lambda x: x.strip(), left)
                # map(lambda x: x.strip(), right)

                # print(left)
                # print(right)

                self.transfer_func[left[0]][left[1]] = right

        # print(self.transfer_func)

    def run(self, base, power):
        belt = ['None'] + ['1'] * power + ['0'] + ['1'] * base + ['0', '1'] + ['None']
        # print('初始纸带:', belt)
        index, state = 1, 'q0'

        def getChar(index):
            if 0 <= index < len(belt):
                return belt[index]
            else:
                belt.append('None')
                return 'None'

        while state != 'final':
            cur_belt = getChar(index)
            newState, replace_char, move = self.transfer_func[state][cur_belt]
            # print('当前位置', index, ' 执行:', state, ' ',  cur_belt, ' = ', newState, ' ', replace_char, ' ', move)
            belt[index] = replace_char
            state = newState
            if move == 'R':
                index += 1
            if move == 'L':
                index -= 1

            # print('当前纸带:', belt, '\n')

        return belt


if __name__ == '__main__':
    path = './Transfer_function.txt'
    TM = TuringMachine()
    TM.readFile(path)

    base = int(input('请输入底数：'))
    power = int(input('请输入幂次：'))
    # print(base, power)

    res = TM.run(base, power)
    res_str = ''.join(res[1:-1])
    print('result:', res)
    print('string:', res_str)
    res_n = res_str.split('0')
    res_n = map(lambda x: len(x), res_n)
    print(list(res_n))
